package web.common.core.message;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.common.core.util.AssertUtil;
import web.common.internal.core.message.DefaultMessageDecoder;
import web.common.internal.core.message.DefaultMessageEncoder;

import java.util.Base64;

/**
 * @author Jin Zheng
 * @since 1.0 2022-01-28
 */
public class MessageCoder {
	private static Logger logger = LoggerFactory.getLogger(MessageCoder.class);

	private MessageCoder() {
	}

	public static byte[] encode(Serializable target) {
		AssertUtil.notNull(target, "Serializable");

		var encoder = new DefaultMessageEncoder();
		target.encode(encoder);
		return encoder.getByteArray();
	}

	public static String encodeBase64(Serializable target) {
		var data = encode(target);
		if (data == null || data.length == 0) {
			return null;
		}
		return Base64.getEncoder().encodeToString(data);
	}

	public static void decode(Serializable target, byte[] data) {
		AssertUtil.notNull(target, "Serializable");
		AssertUtil.notEmpty(data, "Serializable data");

		var decoder = new DefaultMessageDecoder(data);
		target.decode(decoder);
	}

	public static void decode(Serializable target, String base64) {
		AssertUtil.notEmpty(base64, "Serializable data");
		var data = Base64.getDecoder().decode(base64);
		decode(target, data);
	}

}
